package code.remote {

import code.Configuration;

import flash.events.EventDispatcher;

import logging.Logger;

import mx.controls.Alert;
import mx.rpc.events.FaultEvent;
import mx.rpc.events.ResultEvent;
import mx.rpc.http.HTTPService;
import mx.utils.ObjectUtil;
	
[Event(name="resultReceived",type="code.remote.ResultReceivedEvent")]
internal class AbstractRequest extends EventDispatcher {
	
	private static const LOG: Logger = Logger.getLogger("code.remote.AbstractRequest");
	
	private static const ROOT_URL: String = Configuration.REQUEST_ROOT_URL;
	
	
	private var http: HTTPService;
	
	private var requestUrl: String;
	
	public function AbstractRequest(requestType: String) {
		this.requestUrl = ROOT_URL + "?request=" + requestType
		
		this.http = new HTTPService();
		this.http.method = 'POST';
		this.http.useProxy = false;
		this.http.url = this.requestUrl;
		this.http.addEventListener(ResultEvent.RESULT, this._onResult);
		this.http.addEventListener(FaultEvent.FAULT, this.onFault);
	}
	
	/**
	 * @param fnResult(): void
	 */
	public final function doSend(): void {
		
		const xmlData: String = this.getXmlData();
		const params: Object = xmlData != null ? { 'xml_data' : xmlData } : null;
		
		LOG.info("Sending request ["+this.requestUrl+"] with data ["+xmlData+"]");
		this.http.send(params);
	}
	
	private function _onResult(event: ResultEvent): void {
		if(event.result.FatalError != null) {
			LOG.warning(String(event.result.FatalError.Trace));
			throw new Error("Remote ErrorMessage: " + String(event.result.FatalError.Message));
		}
		// LOG.finer("Got result [" + ObjectUtil.toString(event.result) + "]");
		this.onResult(event);
		this.dispatchEvent(new ResultReceivedEvent(event));
	}
	
	/** VIRTUAL */
	protected function onResult(event: ResultEvent): void {
		throw new Error("onResult should have been overridden");
	}
	
	protected function getXmlData(): String {
		return null; // no params by default
	}
	
	protected function onFault(event: FaultEvent): void {
		trace(ObjectUtil.toString(event));
		Alert.show("Request Error", String(event.message));
		//throw new Error("onFault should have been overridden");
	}

}
}